package com.w3c.pragmatic.service.impl;

import com.w3c.pragmatic.service.IRedissonCustomer;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * 定义redisson锁自定义实现
 *
 * @author wangdong
 * @since 2021/12/17 9:34
 */
public class RedissonCustomerImpl implements IRedissonCustomer {

    // 通过自动装配调用set方法注入redissonClient实例到该类
    private RedissonClient redissonClient;

    public void setRedissonClient(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    // ===============================自定义实现包装RedissonClient相关方法================================

    @Override
    public void lock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
    }

    @Override
    public void lock(String lockKey, long timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, TimeUnit.SECONDS);
    }

    @Override
    public void lock(String lockKey, TimeUnit unit, long timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, unit);
    }

    @Override
    public boolean tryLock(String lockKey, TimeUnit unit, long leaseTime)
            throws InterruptedException {
        RLock lock = redissonClient.getLock(lockKey);
        return lock.tryLock(leaseTime, unit);
    }

    @Override
    public boolean tryLock(String lockKey, TimeUnit unit, long leaseTime, long timeout)
            throws InterruptedException {
        RLock lock = redissonClient.getLock(lockKey);
        return lock.tryLock(leaseTime, timeout, unit);
    }

    @Override
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        if (lock.isLocked() && lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }
}
